package service

import (
	"errors"
	"strconv"
	"strings"
	"time"
	"vrcm/src/vrcm/app/admin/models"
	"vrcm/src/vrcm/app/admin/models/monitor"
	dto "vrcm/src/vrcm/app/admin/service/dto/monitor"
	"vrcm/src/vrcm/common/apis"
	cDto "vrcm/src/vrcm/common/dto"
	"vrcm/src/vrcm/common/service"
)

type Worksite struct {
	service.Service
}

// GetPage 获取MonitorBasic列表
func (e *Worksite) GetPage(c *dto.WorksiteGetPageReq, list *[]monitor.Worksite, count *int64) error {
	var err error
	var data monitor.Worksite

	db := e.Orm.Model(&data).
		Scopes(
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		)
	err = db.Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("MonitorBasicService GetPage error:%s \r\n", err)
		return err
	}
	basics := make([]monitor.MonitorBasic, 0, 5)
	if c.EventId > 0 {
		err = e.Orm.Model(&monitor.MonitorBasic{}).Where("bind_id=?", c.EventId).Find(&basics).Error
		if err != nil {
			e.Log.Errorf("get MonitorBasic error:%s \r\n", err)
			return err
		}
	}

	for k, worksite := range *list {
		workSiteAuthority := Deduplication(strings.Trim(worksite.WorkSiteAuthority, models.Delimiter))
		*(&(*list)[k].WorkSiteAuthority) = workSiteAuthority
		for _, basic := range basics {
			basic := basic
			arr := strings.Split(basic.Worksites, ",")
			for _, s := range arr {
				authority, _ := strconv.Atoi(s)
				if authority == worksite.Id {
					*(&(*list)[k].MonitorBasics) = append(*(&(*list)[k].MonitorBasics), basic)
					break
				}
			}
		}
	}

	//ids := make([]int, 0, 5)
	//for _, worksite := range *list {
	//	ids = append(ids, worksite.Id)
	//}

	//basicIds := make([]int, 0, 5)
	//for _, basic := range basics {
	//	basicIds = append(basicIds, basic.Id)
	//}
	//configs := make([]monitor.MonitorConfig, 0, 5)
	//err = e.Orm.Model(&monitor.MonitorConfig{}).Where("basic_id=?", basicIds).Find(&configs).Error
	//if err != nil {
	//	e.Log.Errorf("get MonitorConfig error:%s \r\n", err)
	//	return err
	//}

	return nil
}

func Deduplication(input string) string {
	parts := strings.Split(input, models.Delimiter)

	// 使用 map 来去重
	uniqueMap := make(map[string]struct{})
	for _, part := range parts {
		uniqueMap[part] = struct{}{}
	}
	// 将去重后的结果存入切片
	var uniqueParts []string
	for key := range uniqueMap {
		uniqueParts = append(uniqueParts, key)
	}
	return strings.Join(uniqueParts, "^^")
}

func (e *Worksite) Get(d *dto.WorksiteGetReq) (*monitor.Worksite, error) {
	var model monitor.Worksite
	err := e.Orm.Model(&model).Where("id=?", d.Id).Find(&model).Error
	if err != nil {
		e.Log.Errorf("get Worksite error:%s", err)
		return &model, err
	}
	return &model, nil
}

func (e *Worksite) Insert(c *dto.WorksiteInsertReq) error {
	var err error
	var data monitor.Worksite
	data.TenantId = c.TenantId
	data.WorkSite = c.Worksite
	data.WorkSiteAuthority = c.WorksiteAuthority
	data.WorkSiteType = c.WorksiteType
	data.CreateTime = time.Now().Unix()
	data.UpdateTime = time.Now().Unix()
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("创建Worksite:%s \r\n", err)
		return err
	}
	c.Id = data.Id
	return nil
}

func (e *Worksite) Update(c *dto.WorksiteUpdateReq) error {

	var err error
	var data monitor.Worksite
	err = e.Orm.Model(&monitor.Worksite{}).Where("id=?", c.Id).Find(&data).Error
	if err != nil {
		e.Log.Errorf("get Worksite:%s \r\n", err)
		return err
	}

	data.Id = c.Id
	data.TenantId = c.TenantId
	data.WorkSite = c.Worksite
	data.WorkSiteAuthority = c.WorksiteAuthority
	data.WorkSiteType = c.WorksiteType
	data.UpdateTime = time.Now().Unix()
	err = e.Orm.Save(&data).Error
	if err != nil {
		e.Log.Errorf("更新工口失败:%s \r\n", err)
		return err
	}
	c.Id = data.Id
	return nil
}

func (e *Worksite) Remove(d *dto.WorksiteDeleteReq) error {

	worksiteMember := &monitor.WorksiteMember{}
	err := e.Orm.Model(&monitor.WorksiteMember{}).Where("worksite_id=?", d.Id).Find(&worksiteMember).Error
	if err != nil {
		e.Log.Errorf("WorksiteMember 失败:%s \r\n", err)
		return err
	}

	if worksiteMember.Id > 0 {
		return errors.New(string(apis.DeleteWorksiteError.Code))
	}
	err = e.Orm.Model(&monitor.Worksite{}).Where("id = ?", d.Id).Delete(&monitor.Worksite{}).Error
	if err != nil {
		e.Log.Errorf("删除工口失败:%s \r\n", err)
		return err
	}
	err = e.Orm.Model(&monitor.WorksiteMember{}).Where("worksite_id=?", d.Id).Update("worksite_id", 0).Error
	if err != nil {
		e.Log.Errorf("更新工口:%s ", err)
		return err
	}
	return nil
}

func (e *Worksite) GetWorksiteMember(d *dto.WorksiteMemberGetReq) ([]monitor.Worksite, error) {
	worksites := make([]monitor.Worksite, 0, 5)
	err := e.Orm.Model(&monitor.Worksite{}).Where("tenant_id=?", d.TenantId).Find(&worksites).Error
	if err != nil {
		e.Log.Errorf("get GetWorksiteMember error:%s", err)
		return worksites, err
	}

	worksiteIds := make([]int, 0, 5)
	for _, worksite := range worksites {
		worksiteIds = append(worksiteIds, worksite.Id)
	}
	worksiteMembers := make([]monitor.WorksiteMember, 0, 5)
	err = e.Orm.Model(&monitor.WorksiteMember{}).Where("worksite_id in ?", worksiteIds).Find(&worksiteMembers).Error
	if err != nil {
		e.Log.Errorf("get worksiteMember error:%s", err)
		return worksites, err
	}
	memberMap := make(map[int][]monitor.WorksiteMember)
	for _, member := range worksiteMembers {
		member := member

		members, ok := memberMap[member.WorkSiteId]
		if !ok {
			members = make([]monitor.WorksiteMember, 0, 5)
		}
		members = append(members, member)
		memberMap[member.WorkSiteId] = members
	}

	for k, worksite := range worksites {
		if worksite.Members == nil {
			*(&worksites[k].Members) = make([]monitor.WorksiteMember, 0, 5)
		}
		members, ok := memberMap[worksite.Id]
		if ok {
			*(&worksites[k].Members) = append(*(&worksites[k].Members), members...)
		}
	}

	return worksites, nil
}

func (e *Worksite) GetMemberPage(c *dto.MemberGetPageReq, list *[]monitor.WorksiteMember, count *int64) error {
	var err error
	var data monitor.WorksiteMember

	db := e.Orm.Model(&data).
		Scopes(
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		)
	err = db.Order("LEFT(CONVERT(member_name using gbk), 1)").Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("GetMemberPage error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *Worksite) GetMember(d *dto.MemberGetReq) (*monitor.WorksiteMember, error) {
	var model monitor.WorksiteMember
	err := e.Orm.Model(&model).Where("id=?", d.Id).Find(&model).Error
	if err != nil {
		e.Log.Errorf("get WorksiteMember error:%s", err)
		return &model, err
	}
	return &model, nil
}

func (e *Worksite) GetMemberByAuthority(d *dto.MemberGetByAuthorityReq) ([]monitor.WorksiteMember, error) {
	res := make([]monitor.WorksiteMember, 0, 5)
	models := make([]monitor.WorksiteMember, 0, 5)
	err := e.Orm.Model(&monitor.WorksiteMember{}).Where("tenant_id=?", d.TenantId).Find(&models).Error
	if err != nil {
		e.Log.Errorf("get WorksiteMember error:%s", err)
		return res, err
	}

	ids := make([]int, 0, 5)
	for _, model := range models {
		ids = append(ids, model.WorkSiteId)
	}

	worksites := make([]monitor.Worksite, 0, 5)
	err = e.Orm.Model(&monitor.Worksite{}).Where("id in ?", ids).Find(&worksites).Error
	if err != nil {
		e.Log.Errorf("get Worksite error:%s", err)
		return res, err
	}
	worksiteMap := make(map[int]monitor.Worksite)
	for _, worksite := range worksites {
		worksite := worksite
		worksiteMap[worksite.Id] = worksite
	}

	for _, model := range models {
		model := model
		worksite, _ := worksiteMap[model.WorkSiteId]
		arr := strings.Split(worksite.WorkSiteAuthority, "^^")
		isSame := false
		for _, s := range arr {
			if s == strconv.Itoa(d.Authority) {
				isSame = true
				break
			}
		}
		if isSame {
			res = append(res, model)
		}
	}

	return res, nil
}

func (e *Worksite) InsertMember(c *dto.MemberInsertReq) error {
	var err error
	var data monitor.WorksiteMember
	data.TenantId = c.TenantId
	data.MemberName = c.MemberName
	data.MobilePhone = c.MobilePhone
	data.MemberAccount = c.MemberAccount
	data.WorkSiteId = c.WorkSiteId
	data.CreateTime = time.Now().Unix()
	data.UpdateTime = time.Now().Unix()
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("创建Member:%s \r\n", err)
		return err
	}
	c.Id = data.Id
	return nil
}

func (e *Worksite) UpdateMember(c *dto.MemberUpdateReq) error {

	var err error
	var data monitor.WorksiteMember
	err = e.Orm.Model(&monitor.WorksiteMember{}).Where("id=?", c.Id).Find(&data).Error
	if err != nil {
		e.Log.Errorf("get WorksiteMember:%s \r\n", err)
		return err
	}

	data.Id = c.Id
	data.TenantId = c.TenantId
	data.MemberName = c.MemberName
	data.MobilePhone = c.MobilePhone
	data.MemberAccount = c.MemberAccount
	data.WorkSiteId = c.WorkSiteId
	data.UpdateTime = time.Now().Unix()
	err = e.Orm.Save(&data).Error
	if err != nil {
		e.Log.Errorf("更新成员失败:%s \r\n", err)
		return err
	}
	c.Id = data.Id
	return nil
}

func (e *Worksite) RemoveMember(d *dto.MemberDeleteReq) error {

	eventMember := &monitor.EventMember{}
	err := e.Orm.Model(&monitor.EventMember{}).Where("member_id=?", d.Id).Find(&eventMember).Error
	if err != nil {
		e.Log.Errorf("获取活动成员失败:%s \r\n", err)
		return err
	}

	if eventMember.Id > 0 {
		return errors.New(string(apis.DeleteWorksiteMemberError.Code))
	}
	err = e.Orm.Model(&monitor.WorksiteMember{}).Where("id = ?", d.Id).Delete(&monitor.WorksiteMember{}).Error
	if err != nil {
		e.Log.Errorf("删除成员失败:%s \r\n", err)
		return err
	}
	return nil
}

func (e *Worksite) SaveWorksiteNotice(c *dto.WorksiteNoticeInsertReq) error {
	var err error
	data := make([]monitor.WorksiteNotice, 0, 5)

	//err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("event_id=? and program_id=?", c.EventId, c.ProgramId).Delete(&monitor.WorksiteNotice{}).Error
	//if err != nil {
	//	e.Log.Errorf("delete WorksiteNotice error:%s \r\n", err)
	//	return err
	//}

	updateIds := make([]int, 0, 5)
	for _, notice := range c.WorksiteNotices {
		if notice.Id > 0 {
			updateIds = append(updateIds, notice.Id)
		}
	}
	updateWorksiteNotices := make([]monitor.WorksiteNotice, 0, 5)
	err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("id in ?", updateIds).Find(&updateWorksiteNotices).Error
	if err != nil {
		e.Log.Errorf("update WorksiteNotice error:%s \r\n", err)
		return err
	}

	updateWorksiteNoticeMap := make(map[int]monitor.WorksiteNotice)
	for _, notice := range updateWorksiteNotices {
		notice := notice
		updateWorksiteNoticeMap[notice.Id] = notice
	}

	now := time.Now().Unix()
	for _, notice := range c.WorksiteNotices {
		worksiteNotice := monitor.WorksiteNotice{}
		worksiteNotice.Id = notice.Id
		worksiteNotice.Notice = notice.Notice
		worksiteNotice.TenantId = c.TenantId
		worksiteNotice.EventId = c.EventId
		worksiteNotice.WorkSiteId = notice.WorksiteIds
		if notice.Id <= 0 {
			worksiteNotice.IsSend = 2
			worksiteNotice.NoticeState = 2
			worksiteNotice.Duration = 10
		} else {
			tempNotice, ok := updateWorksiteNoticeMap[notice.Id]
			if ok {
				worksiteNotice.NoticeState = tempNotice.NoticeState
				worksiteNotice.StateUpdateTime = tempNotice.StateUpdateTime
				worksiteNotice.Duration = tempNotice.Duration
			}
		}

		worksiteNotice.ProgramId = notice.ProgramId
		if notice.Id <= 0 {
			worksiteNotice.CreateTime = now
		}
		data = append(data, worksiteNotice)
	}

	if len(c.DelIds) > 0 {
		err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("id in ?", c.DelIds).Delete(&monitor.WorksiteNotice{}).Error
		if err != nil {
			e.Log.Errorf("delete WorksiteNotice error:%s \r\n", err)
			return err
		}
	}

	if len(data) > 0 {
		err = e.Orm.Save(&data).Error
		if err != nil {
			e.Log.Errorf("SaveWorksiteMember error:%s \r\n", err)
			return err
		}
	}

	return nil
}

func (e *Worksite) UpdateWorksiteNotice(c *dto.WorksiteNoticeUpdateReq) error {

	worksiteNotice := monitor.WorksiteNotice{}
	err := e.Orm.Model(&monitor.WorksiteNotice{}).Where("id=?", c.Id).Find(&worksiteNotice).Error
	if err != nil {
		e.Log.Errorf("get WorksiteNotice error:%s \r\n", err)
		return err
	}
	worksiteNotice.WorkSiteId = c.WorksiteIds
	worksiteNotice.Notice = c.Notice
	worksiteNotice.Duration = c.Duration
	err = e.Orm.Save(worksiteNotice).Error
	if err != nil {
		e.Log.Errorf("save WorksiteNotice error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *Worksite) ExportWorksiteNotice(c *dto.ExportWorksiteNoticeReq) error {
	var err error
	data := make([]monitor.WorksiteNotice, 0, 5)

	if len(c.ProgramId) > 0 {
		err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("program_id=? ", c.ProgramId).Delete(&monitor.WorksiteNotice{}).Error
		if err != nil {
			e.Log.Errorf("delete WorksiteNotice error:%s \r\n", err)
			return err
		}
		err = e.Orm.Model(&monitor.TaiBen{}).Where("program_id=? ", c.ProgramId).Delete(&monitor.TaiBen{}).Error
		if err != nil {
			e.Log.Errorf("delete TaiBen error:%s \r\n", err)
			return err
		}
	} else {
		err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("event_id=? ", c.EventId).Delete(&monitor.WorksiteNotice{}).Error
		if err != nil {
			e.Log.Errorf("delete WorksiteNotice error:%s \r\n", err)
			return err
		}
		err = e.Orm.Model(&monitor.TaiBen{}).Where("event_id=? ", c.EventId).Delete(&monitor.TaiBen{}).Error
		if err != nil {
			e.Log.Errorf("delete TaiBen error:%s \r\n", err)
			return err
		}
	}

	now := time.Now().Unix()
	for _, program := range c.ProgramWorksiteNotices {

		for _, notice := range program.WorksiteNotices {
			worksiteNotice := monitor.WorksiteNotice{}
			worksiteNotice.Id = notice.Id
			worksiteNotice.Notice = notice.Notice
			worksiteNotice.TenantId = c.TenantId
			worksiteNotice.EventId = c.EventId
			worksiteNotice.WorkSiteId = notice.WorksiteIds
			if notice.Id <= 0 {
				worksiteNotice.NoticeState = 2
				worksiteNotice.Duration = 10
			}

			worksiteNotice.ProgramId = notice.ProgramId
			if notice.Id <= 0 {
				worksiteNotice.CreateTime = now
			}
			data = append(data, worksiteNotice)
		}
	}

	taiben := make([]monitor.TaiBen, 0, 5)
	for _, req := range c.TaiBen {
		for _, ben := range req.TaiBen {
			ben.EventId = req.EventId
			ben.TenantId = req.TenantId
			ben.ProgramId = req.ProgramId
			ben.CreateTime = now
			ben.UpdateTime = now
			taiben = append(taiben, ben)
		}
	}
	if len(taiben) > 0 {
		err = e.Orm.Save(&taiben).Error
		if err != nil {
			e.Log.Errorf("SaveTaiBen error:%s \r\n", err)
			return err
		}
	}
	if len(data) > 0 {
		err = e.Orm.Save(&data).Error
		if err != nil {
			e.Log.Errorf("SaveWorksiteMember error:%s \r\n", err)
			return err
		}
	}

	return nil
}

func (e *Worksite) SetWorksiteNoticeDuration(c *dto.SetWorksiteNoticeDurationReq) error {

	err := e.Orm.Model(&monitor.WorksiteNotice{}).Where("id=? ", c.Id).Update("duration", c.Duration).Error
	if err != nil {
		e.Log.Errorf("SetWorksiteNoticeDuration error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *Worksite) DeleteWorksiteNotice(c *dto.WorksiteNoticeDeleteReq) error {
	var err error
	err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("event_id=? and program_id=?", c.EventId, c.ProgramId).Delete(&monitor.WorksiteNotice{}).Error
	if err != nil {
		e.Log.Errorf("delete WorksiteNotice error:%s \r\n", err)
		return err
	}
	return err
}

func (e *Worksite) GetWorksiteNotice(c *dto.WorksiteNoticeGetReq) ([]monitor.WorksiteNotice, error) {

	var err error

	worksiteNotices := make([]monitor.WorksiteNotice, 0, 5)
	db := e.Orm.Model(&monitor.WorksiteNotice{}).Where("event_id=?", c.EventId)

	if len(c.ProgramId) > 0 {
		db = db.Where("program_id=?", c.ProgramId)
	}

	err = db.Find(&worksiteNotices).Error
	if err != nil {
		e.Log.Errorf("get WorksiteNotice error:%s \r\n", err)
		return worksiteNotices, err
	}

	worksiteMap := make(map[string]struct{})
	worksiteIds := make([]int, 0, 5)
	for _, notice := range worksiteNotices {
		worksites := strings.Split(notice.WorkSiteId, ",")
		for _, worksite := range worksites {
			_, ok := worksiteMap[worksite]
			if !ok {
				worksiteId, _ := strconv.Atoi(worksite)
				worksiteIds = append(worksiteIds, worksiteId)
			}
		}
	}

	worksites := make([]monitor.Worksite, 0, 5)
	err = e.Orm.Model(&monitor.Worksite{}).Where("id in ?", worksiteIds).Find(&worksites).Error
	if err != nil {
		e.Log.Errorf("get Worksite error:%s \r\n", err)
		return worksiteNotices, err
	}

	realWorksiteMap := make(map[int]monitor.Worksite)
	for _, worksite := range worksites {
		worksite := worksite
		realWorksiteMap[worksite.Id] = worksite
	}

	worksiteString := ""
	for k, notice := range worksiteNotices {
		worksites := strings.Split(notice.WorkSiteId, ",")
		for _, worksite := range worksites {
			worksiteId, _ := strconv.Atoi(worksite)
			worksite := realWorksiteMap[worksiteId]
			worksiteString += worksite.WorkSite + ","
		}
		*(&worksiteNotices[k].WorkSite) = strings.Trim(worksiteString, ",")
	}

	return worksiteNotices, err
}

var tempWorksiteNoticeMap = make(map[string][]monitor.WorksiteNotice)

func (e *Worksite) GetWorksiteNotices(c *dto.WorksiteNoticeGetReq) (monitor.WorksiteNotices, error) {

	model := monitor.WorksiteNotices{}
	worksiteNotices := make([]monitor.WorksiteNotice, 0, 5)
	err := e.Orm.Model(&monitor.WorksiteNotice{}).Where("event_id=? and program_id=?", c.EventId, c.ProgramId).Find(&worksiteNotices).Error
	if err != nil {
		e.Log.Errorf("get WorksiteNotice error:%s \r\n", err)
		return model, err
	}

	ids := make([]int, 0, 5)
	for _, notice := range worksiteNotices {
		ids = append(ids, notice.Id)
	}

	worksiteConfirms := make([]monitor.WorksiteConfirm, 0, 5)
	err = e.Orm.Model(&monitor.WorksiteConfirm{}).Where("notice_id in ?", ids).Find(&worksiteConfirms).Error
	if err != nil {
		e.Log.Errorf("get WorksiteConfirm error:%s \r\n", err)
		return model, err
	}

	confirmMap := make(map[int][]int)
	for _, confirm := range worksiteConfirms {
		confirm := confirm
		worksiteIds, ok := confirmMap[confirm.NoticeId]
		if !ok {
			worksiteIds = make([]int, 0, 4)
		}
		worksiteIds = append(worksiteIds, confirm.WorksiteId)
		confirmMap[confirm.NoticeId] = worksiteIds
	}

	e.Log.Trace("KKKKKJJHKJHKJHKHKJHKH:", confirmMap)
	key := strconv.Itoa(c.EventId) + "^^" + c.ProgramId
	//比较上一次和这一次消息变化
	notices, _ := tempWorksiteNoticeMap[key]
	if len(notices) != len(worksiteNotices) {
		model.UpdateState = 1
	} else {
		for _, notice := range notices {
			isChange := true
			for _, worksiteNotice := range worksiteNotices {
				if notice.Notice == worksiteNotice.Notice && notice.WorkSiteId == worksiteNotice.WorkSiteId {
					isChange = false
					break
				}
			}
			if isChange {
				model.UpdateState = 1
				break
			}
		}
	}

	tempWorksiteNoticeMap = make(map[string][]monitor.WorksiteNotice)
	notices = make([]monitor.WorksiteNotice, 0, 5)
	for _, notice := range worksiteNotices {
		notice := notice
		notices = append(notices, notice)
	}

	worksiteMap := make(map[string]struct{})
	worksiteIds := make([]int, 0, 5)
	for _, notice := range worksiteNotices {
		worksites := strings.Split(notice.WorkSiteId, ",")
		for _, worksite := range worksites {
			_, ok := worksiteMap[worksite]
			if !ok {
				worksiteId, _ := strconv.Atoi(worksite)
				worksiteIds = append(worksiteIds, worksiteId)
			}
		}
	}

	worksites := make([]monitor.Worksite, 0, 5)
	err = e.Orm.Model(&monitor.Worksite{}).Where("id in ?", worksiteIds).Find(&worksites).Error
	if err != nil {
		e.Log.Errorf("get Worksite error:%s \r\n", err)
		return model, err
	}

	realWorksiteMap := make(map[int]monitor.Worksite)
	for _, worksite := range worksites {
		worksite := worksite
		realWorksiteMap[worksite.Id] = worksite
	}

	for k, notice := range worksiteNotices {
		worksites := strings.Split(notice.WorkSiteId, ",")
		worksiteString := ""
		for _, worksite := range worksites {
			info := monitor.WorkSiteInfo{}
			worksiteId, _ := strconv.Atoi(worksite)
			if worksiteId > 0 {
				worksite := realWorksiteMap[worksiteId]
				worksiteString += worksite.WorkSite + ","
				info.WorkSiteId = worksiteId
				info.WorkSite = worksite.WorkSite
				*(&worksiteNotices[k].WorkSiteInfos) = append(*(&worksiteNotices[k].WorkSiteInfos), info)
			}
		}
		*(&worksiteNotices[k].WorkSite) = strings.Trim(worksiteString, ",")
		worksiteIds, ok := confirmMap[notice.Id]
		if ok {
			worksiteIdString := ""
			for _, id := range worksiteIds {
				id := id
				worksiteIdString += strconv.Itoa(id) + ","
			}
			*(&worksiteNotices[k].ConfirmWorkSite) = strings.Trim(worksiteIdString, ",")
		}

	}

	tempWorksiteNoticeMap[key] = notices
	model.WorksiteNotices = worksiteNotices
	return model, err
}

var tempWorksiteNotice = monitor.WorksiteNotice{}

func (e *Worksite) GetWorksiteNoticeHistory(c *dto.WorksiteNoticeGetReq) (monitor.WorksiteNoticeHistoryModel, error) {

	model := monitor.WorksiteNoticeHistoryModel{}
	worksiteNotices := make([]monitor.WorksiteNoticeHistory, 0, 5)
	db := e.Orm.Model(&monitor.WorksiteNoticeHistory{}).Where("event_id=?", c.EventId)
	if len(c.ProgramId) > 0 {
		db.Where("program_id=?", c.EventId)
	}
	//db.Order("state_update_time desc")
	db.Order("create_time desc")

	err := db.Find(&worksiteNotices).Error
	if err != nil {
		e.Log.Errorf("get GetWorksiteNoticeHistory error:%s \r\n", err)
		return model, err
	}

	ids := make([]int, 0, 5)
	for _, notice := range worksiteNotices {
		ids = append(ids, notice.Id)
	}

	worksiteConfirms := make([]monitor.WorksiteConfirm, 0, 5)
	err = e.Orm.Model(&monitor.WorksiteConfirm{}).Where("notice_id in ?", ids).Find(&worksiteConfirms).Error
	if err != nil {
		e.Log.Errorf("get WorksiteConfirm error:%s \r\n", err)
		return model, err
	}

	worksiteIds := make([]int, 0, 3)
	for _, notice := range worksiteNotices {

		arr := strings.Split(notice.WorkSiteId, ",")
		tempInt := make([]int, 0, 3)
		for _, s := range arr {
			h, _ := strconv.Atoi(s)
			tempInt = append(tempInt, h)
		}
		worksiteIds = append(worksiteIds, tempInt...)
	}

	confirmMap := make(map[int][]int)
	for _, confirm := range worksiteConfirms {
		confirm := confirm
		worksiteIds, ok := confirmMap[confirm.NoticeId]
		if !ok {
			worksiteIds = make([]int, 0, 4)
		}
		worksiteIds = append(worksiteIds, confirm.WorksiteId)
		confirmMap[confirm.NoticeId] = worksiteIds
	}

	worksites := make([]monitor.Worksite, 0, 5)
	err = e.Orm.Model(&monitor.Worksite{}).Where("id in ?", worksiteIds).Find(&worksites).Error
	if err != nil {
		e.Log.Errorf("get Worksite error:%s \r\n", err)
		return model, err
	}

	realWorksiteMap := make(map[int]monitor.Worksite)
	for _, worksite := range worksites {
		worksite := worksite
		realWorksiteMap[worksite.Id] = worksite
	}

	for k, notice := range worksiteNotices {
		worksites := strings.Split(notice.WorkSiteId, ",")
		worksiteString := ""
		for _, worksite := range worksites {
			worksiteId, _ := strconv.Atoi(worksite)
			info := monitor.WorkSiteInfo{}
			if worksiteId > 0 {
				worksite := realWorksiteMap[worksiteId]
				worksiteString += worksite.WorkSite + ","
				info.WorkSiteId = worksiteId
				info.WorkSite = worksite.WorkSite
				*(&worksiteNotices[k].WorkSiteInfos) = append(*(&worksiteNotices[k].WorkSiteInfos), info)
			}
		}
		*(&worksiteNotices[k].WorkSite) = strings.Trim(worksiteString, ",")
		worksiteIds, ok := confirmMap[notice.Id]
		if ok {
			worksiteIdString := ""
			for _, id := range worksiteIds {
				id := id
				worksiteIdString += strconv.Itoa(id) + ","
			}
			*(&worksiteNotices[k].ConfirmWorkSite) = strings.Trim(worksiteIdString, ",")
		}

	}
	model.WorksiteNotices = worksiteNotices

	return model, err
}

func (e *Worksite) SendWorksiteNotice(c *dto.WorksiteNoticeSendReq) error {

	//获取工口消息
	worksiteNotice := &monitor.WorksiteNotice{}
	err := e.Orm.Model(&monitor.WorksiteNotice{}).Where("event_id=? and program_id=?", c.EventId, c.ProgramId).Find(&worksiteNotice).Error
	if err != nil {
		e.Log.Errorf("get WorksiteNotice error:%s ", err)
		return err
	}

	workSiteHistory := monitor.WorksiteNoticeHistory{}
	now := time.Now().Unix()
	if c.Id > 0 {
		param := make(map[string]interface{})
		param["duration"] = c.Duration
		param["is_send"] = c.IsSend
		param["notice_state"] = 1
		param["state_update_time"] = time.Now().Unix()
		err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("id = ?", c.Id).Updates(&param).Error
		if err != nil {
			e.Log.Errorf("SendWorksiteNotice error:%s \r\n", err)
			return err
		}
		worksiteNotice := &monitor.WorksiteNotice{}
		err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("id = ?", c.Id).Find(&worksiteNotice).Error
		if err != nil {
			e.Log.Errorf("get worksiteNotice error:%s \r\n", err)
			return err
		}

		workSiteHistory.TenantId = worksiteNotice.TenantId
		workSiteHistory.EventId = worksiteNotice.EventId
		workSiteHistory.WorkSiteId = worksiteNotice.WorkSiteId
		workSiteHistory.Notice = worksiteNotice.Notice
		workSiteHistory.ProgramId = worksiteNotice.ProgramId
		workSiteHistory.Duration = worksiteNotice.Duration
		//workSiteHistory.NoticeState = worksiteNotice.NoticeState
	} else {
		workSiteHistory.TenantId = c.TenantId
		workSiteHistory.EventId = c.EventId
		workSiteHistory.WorkSiteId = c.WorkSiteId
		workSiteHistory.Notice = c.Notice
		workSiteHistory.ProgramId = c.ProgramId
		workSiteHistory.Duration = c.Duration
	}
	workSiteHistory.NoticeId = c.Id
	workSiteHistory.CreateTime = now
	workSiteHistory.UpdateTime = now
	err = e.Orm.Save(&workSiteHistory).Error
	if err != nil {
		e.Log.Errorf("save workSiteHistory error:%s ", err)
		return err
	}

	err = e.Orm.Model(&monitor.WorksiteConfirm{}).Where("notice_id=?", c.Id).Delete(&monitor.WorksiteConfirm{}).Error
	if err != nil {
		e.Log.Errorf("delete WorksiteNotice error:%s ", err)
		return err
	}

	return err
}

func (e *Worksite) IsExitWorksiteMember(c *dto.MemberUpdateReq) bool {

	var basic monitor.WorksiteMember
	var err error

	basicWhere := monitor.WorksiteMember{MemberAccount: c.MemberAccount, TenantId: c.TenantId}
	if c.Id > 0 {
		err = e.Orm.Where(&basicWhere).Not("id =?", c.Id).Find(&basic).Error
	} else {
		err = e.Orm.Where(&basicWhere).Find(&basic).Error
	}

	if err != nil {
		return true
	}

	if basic.Id > 0 {
		return true
	}
	return false
}

func (e *Worksite) IsExitWorksite(c *dto.WorksiteUpdateReq) bool {

	var basic monitor.Worksite
	var err error

	basicWhere := monitor.Worksite{WorkSite: c.Worksite, TenantId: c.TenantId}
	if c.Id > 0 {
		err = e.Orm.Where(&basicWhere).Not("id =?", c.Id).Find(&basic).Error
	} else {
		err = e.Orm.Where(&basicWhere).Find(&basic).Error
	}

	if err != nil {
		return true
	}

	if basic.Id > 0 {
		return true
	}
	return false
}

func (e *Worksite) SetWorksiteAuthority(c *dto.SetWorksiteAuthorityReq) error {

	ids := make([]int, 0, 5)
	worksiteAuthorityMap := make(map[int]dto.WorksiteAuthority)
	for _, authority := range c.WorksiteAuthority {
		authority := authority
		worksiteAuthorityMap[authority.Id] = authority
		ids = append(ids, authority.Id)
	}
	worksites := make([]monitor.Worksite, 0, 5)
	err := e.Orm.Model(&monitor.Worksite{}).Where("id in ? ", ids).Find(&worksites).Error
	if err != nil {
		e.Log.Errorf("SetWorksiteAuthority error:%s \r\n", err)
		return err
	}

	for k, worksite := range worksites {

		authority, ok := worksiteAuthorityMap[worksite.Id]
		if !ok {
			continue
		}

		if authority.SetType == 1 {
			*(&worksites[k].WorkSiteAuthority) = worksite.WorkSiteAuthority + models.Delimiter + strconv.Itoa(authority.Authority)
		} else {
			arr := strings.Split(worksite.WorkSiteAuthority, models.Delimiter)
			tempArr := make([]string, 0, 3)
			for _, s := range arr {
				s := s
				if s == strconv.Itoa(authority.Authority) {
					continue
				}
				tempArr = append(tempArr, s)
			}
			*(&worksites[k].WorkSiteAuthority) = strings.Join(tempArr, models.Delimiter)
		}
	}

	if len(worksites) > 0 {
		err = e.Orm.Save(&worksites).Error
		if err != nil {
			e.Log.Errorf("save worksites error:%s \r\n", err)
			return err
		}
	}

	return nil
}

func (e *Worksite) SaveTaiBen(c *dto.TaiBenInsertReq) error {
	var err error

	if len(c.DelIds) > 0 {
		err = e.Orm.Model(&monitor.TaiBen{}).Where("id in ?", c.DelIds).Delete(&monitor.TaiBen{}).Error
		if err != nil {
			e.Log.Errorf("delete TaiBen error:%s \r\n", err)
			return err
		}
	}

	now := time.Now().Unix()
	for k, ben := range c.TaiBen {
		*(&c.TaiBen[k].EventId) = c.EventId
		*(&c.TaiBen[k].TenantId) = c.TenantId
		*(&c.TaiBen[k].ProgramId) = c.ProgramId
		if ben.Id > 0 {
			*(&c.TaiBen[k].UpdateTime) = now
		} else {
			*(&c.TaiBen[k].CreateTime) = now
			*(&c.TaiBen[k].UpdateTime) = now
		}

	}

	if len(c.TaiBen) > 0 {
		err = e.Orm.Save(&c.TaiBen).Error
		if err != nil {
			e.Log.Errorf("SaveTaiBen error:%s \r\n", err)
			return err
		}
	}

	return nil
}

func (e *Worksite) GetTaiBen(c *dto.TaiBenGetReq) ([]monitor.TaiBen, error) {

	taiben := make([]monitor.TaiBen, 0, 5)
	db := e.Orm.Model(&monitor.TaiBen{}).Where("event_id=?", c.EventId)
	if len(c.ProgramId) > 0 {
		db.Where("program_id =?", c.ProgramId)
	}
	err := db.Find(&taiben).Error
	if err != nil {
		e.Log.Errorf("GetTaiBen error:%s \r\n", err)
		return taiben, err
	}

	return taiben, nil
}

func (e *Worksite) DeleteTaiBen(c *dto.TaiBenDeleteReq) error {

	err := e.Orm.Model(&monitor.TaiBen{}).Where("id in ?", c.Ids).Delete(&monitor.TaiBen{}).Error
	if err != nil {
		e.Log.Errorf("DeleteTaiBen error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *Worksite) NoticeConfirm(c *dto.NoticeConfirm) error {
	worksiteConfirm := &monitor.WorksiteConfirm{
		NoticeId:   c.NoticeId,
		WorksiteId: c.WorksiteId,
	}
	err := e.Orm.Model(&monitor.WorksiteConfirm{}).Create(&worksiteConfirm).Error
	if err != nil {
		e.Log.Errorf("NoticeConfirm error:%s \r\n", err)
		return err
	}
	return nil
}
